package com.hrms.intercept;

import com.hrms.annotation.UserIgnore;
import com.hrms.entity.User;
import com.hrms.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.lang.annotation.Annotation;

@Component
public class UserInterceptor implements HandlerInterceptor {
    // 用户端的拦截器

    @Autowired
    private UserService userService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Annotation ignore =  handlerMethod.getMethodAnnotation(UserIgnore.class);
        // 不拦截
        if(ignore != null) {
            return true;
        }

        User user = new User();
        user.setUser_id(Integer.valueOf(request.getHeader("User-Id")));
        user.setUser_status("在线");
        if(!userService.checkStatue(user)) {
            // 置状态码为401
            System.out.println("401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        return true;
    }
}
